//
//  AdviceController.m
//  Nurse
//
//  Created by Sunny on 13-12-21.
//  Copyright (c) 2013年 RainSets. All rights reserved.
//

#import "AdviceController.h"
#import "AdviceDetailCell.h"
#import "PatientService.h"
#import "OrdersService.h"
#import "EGORefreshTableHeaderView.h"  //下来刷新
@interface AdviceController (){
    
}

@property(nonatomic,strong) IBOutlet UITableView *table;
@property (nonatomic,strong) NSArray* patientOrders;
@end

@implementation AdviceController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//    if (self) {
//        // Custom initialization
//    }
//    
//
//    return self;
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setupData];
           }
    return self;

}

-(void)setupData{
    NSDictionary* Patient = [[PatientService sharedInstance]currentPatient];
    if ([Patient count] > 0) {
        NSString* zyh = [Patient valueForKey:@"住院号"];
        __weak AdviceController* this = self;
        // [OrdersService queryPatientsForOrders:zyh withSuccessHandler:^(id result) {
        [[OrdersService sharedInstance]queryOrdersForPatient:zyh withSuccessHandler:^(id result) {
            if ([result isKindOfClass:[NSArray class]]) {
                //NSLog(@"patient order %@.............",result);
                this.patientOrders = result;
                [this.table reloadData];
            }
        } andFailHandler:^(NSError *error, NSString *title) {
            [[DataEngine sharedInstance]showMessage:[error description] withTitle:@"访问病人医嘱数据错误"];
        }];
    }else{
        [[DataEngine sharedInstance]showMessage:@"没有病人的医嘱信息" withTitle:@"数据错误"];
    }


}

- (void)reloadTableViewDataSource{
    _reloading = YES;
    //开始刷新后执行后台线程，在此之前可以开启HUD或其他对UI进行阻塞
    //[NSThread detachNewThreadSelector:@selector(doInBackground) toTarget:self withObject:nil];
    //[self setupData];
    
}

//下拉松开刷新
- (void)doneLoadingTableViewData{
    NSLog(@"===加载完数据");
    _reloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.table];
    [self setupData];
}
#pragma mark –
#pragma mark UIScrollViewDelegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
} - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}
#pragma mark –
#pragma mark EGORefreshTableHeaderDelegate Methods
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    [self reloadTableViewDataSource];
    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:3.0];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
    return _reloading;
}
- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
    return [NSDate date];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"医嘱";
    // Do any additional setup after loading the view from its nib.
    NSDictionary* patient = [[PatientService sharedInstance]currentPatient];
    
    self.pInfoView.txtPatientName.text = [patient valueForKey:@"姓名"];
    self.pInfoView.txtPatientID.text = [NSString stringWithFormat:@"住院号:%@",[patient valueForKey:@"住院号"]];
    self.pInfoView.txtBedNo.text = [NSString stringWithFormat:@"床位号:%@",[patient valueForKey:@"床位号"]];
    NSString*xb= [patient valueForKey:@"性别"];
    if ([xb isEqualToString:@"女"]) {
        self.pInfoView.imgxb.image=[UIImage imageNamed:@"gender-female2.png"];
        
    }
    else{
        self.pInfoView.imgxb.image=[UIImage imageNamed:@"gender-male2.png"];
    }
    
    if (_refreshHeaderView == nil) {
        EGORefreshTableHeaderView *view1 = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0-self.table.bounds.size.height, self.view.frame.size.width, self.table.bounds.size.height)];
        view1.delegate = self;
        [self.table addSubview:view1];
        _refreshHeaderView = view1;
        // [view1 release];
    }
    [_refreshHeaderView refreshLastUpdatedDate];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
  
    
    return 100.f;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger count = [self.patientOrders count];
        
                return count;

}


- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return UITableViewCellEditingStyleNone;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *identify = @"AdviceDetailCell";
    //BedCell *cell = (BedCell *)[tableView  dequeueReusableCellWithIdentifier:identify];

    AdviceDetailCell *cell =(AdviceDetailCell*) [tableView  dequeueReusableCellWithIdentifier:identify];
    if (!cell ) {
        NSArray *ibs = [[NSBundle mainBundle] loadNibNamed:@"AdviceDetailCell" owner:self options:nil];
        cell = (AdviceDetailCell *)[ibs objectAtIndex:0];
        // cell.selectionStyle = UITableViewCellSelectionStyleGray;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    NSInteger row = [indexPath row];
    NSDictionary* record = [self.patientOrders objectAtIndex:row];
    
//    
//    for (int i=0; i<row; i++) {
    if (cell != nil) {
        cell.lblTime.hidden = NO;
        cell.imgFlag.hidden = NO;
        cell.lblhx.hidden =NO;
        cell.lblNurse.hidden=YES;
        cell.imgzb.hidden=NO;
        //cell.backgroundColor= [UIColor colorWithRed:235/255.0 green:239/255.0 blue:245/255.0 alpha:0.6];
        cell.lblTime.text=[[record valueForKey:@"开始日期"] substringToIndex:2];
        //[NSString stringWithFormat:@"%@\n%@",[record valueForKey:@"开始日期"],[record valueForKey:@"开始时间"]];
        NSString*month=[[record valueForKey:@"开始日期"] substringWithRange:NSMakeRange(3,2)];
        
        
        if ([month isEqualToString:@"01"])
        {
            month=@"一月";
        }
        if ([month isEqualToString:@"02"])
        {
            month=@"二月";
        }
        if ([month isEqualToString:@"03"])
        {
            month=@"三月";
        }
        if ([month isEqualToString:@"04"])
        {
            month=@"四月";
        }
        if ([month isEqualToString:@"05"])
        {
            month=@"五月";
        }
        if ([month isEqualToString:@"06"])
        {
            month=@"六月";
        }
        if ([month isEqualToString:@"07"])
        {
            month=@"七月";
        }
        if ([month isEqualToString:@"08"])
        {
            month=@"八月";
        }
        if ([month isEqualToString:@"09"])
        {
            month=@"九月";
        }
        if ([month isEqualToString:@"10"])
        {
            month=@"十月";
        }
        if ([month isEqualToString:@"11"])
        {
            month=@"十一月";
        }
        if ([month isEqualToString:@"12"])
        {
            month=@"十二月";
        }
        
        cell.lblyf.text=month;
        cell.lblsj.text=[record valueForKey:@"开始时间"];
        
        
//        NSString*year=[[record valueForKey:@"申请日期"] substringToIndex:4];
//        NSString*month=[[record valueForKey:@"申请日期"] substringWithRange:NSMakeRange(5,2)];
        cell.lblTitle.text = [record valueForKey:@"医嘱内容"];
        cell.lblDoc.text = [NSString stringWithFormat:@"下嘱医生:%@",[record valueForKey:@"下嘱医师"]];
        cell.lblDose.text = [NSString stringWithFormat:@"%@ %@",[record valueForKey:@"剂量"],[record valueForKey:@"单位"]];
        cell.lblWay.text = [NSString stringWithFormat:@"%@  %@",[record valueForKey:@"途径"],[record valueForKey:@"频次"]];
        cell.lblgg.text=[record valueForKey:@"规格"];
        NSString* yzsx=[record valueForKey:@"医嘱属性"];
        if( [yzsx isEqual:@"临时"])
        {
            cell.imgVState.image=[UIImage imageNamed:@"advise-icon_02.png"];
        }
        else
        {
          cell.imgVState.image=[UIImage imageNamed:@"advise-icon_01.png"];
        }
            
        NSString* zbbz=[record valueForKey:@"自备标志"];
        if (![zbbz isEqualToString:@"是"]) {
            cell.imgzb.hidden=YES;
        }

        NSString* zyzbh = [record valueForKey:@"主医嘱编号"];
        NSString* yzbh = [record valueForKey:@"医嘱编号"];
        if (![zyzbh isEqualToString:yzbh]) {
            cell.lblTime.hidden = YES;
            cell.imgFlag.hidden = YES;
            //cell.lblhx.hidden=YES;
            cell.lblhx.frame = CGRectMake(67.0f, 0.0f, 290.0f, 1.0f);
            
        }
    
       // NSLog(@"主医嘱编号:%@,医嘱编号%@",zyzbh,yzbh );
        
    }
//    }
    
    //    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    return  cell;
   }


@end
